<script setup>
import { ref, watch, onMounted } from 'vue';
import { getEmpListApi, addEmpApi,updateEmpApi,deleteEmpApi } from '@/api/emp'
import { getDeptListApi } from '@/api/dept'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getEmpByIdApi } from '../../api/emp';

//职位列表数据
const jobs = ref([{ name: '班主任', value: 1 },{ name: '讲师', value: 2 },{ name: '学工主管', value: 3 },{ name: '教研主管', value: 4 },{ name: '咨询师', value: 5 },{ name: '其他', value: 6 }])
//性别列表数据
const genders = ref([{ name: '男', value: 1 }, { name: '女', value: 2 }])

// 部门列表数据
const depts = ref([])

// 表单数据
const searchEmp = ref({
  name: '',
  gender: '',
  date: [],
  begin: '',
  end: ''
});

// 提交处理函数
const searchEmps = async () => {
  console.log('Submit:', searchEmp.value);
  const result = await getEmpListApi(searchEmp.value.name, searchEmp.value.gender, searchEmp.value.begin, searchEmp.value.end, currentPage.value, pageSize.value)
  empList.value = result.data.rows;
  totalRecords.value = result.data.total;
};

// 重置表单数据
const clear = () => {
  searchEmp.value = {
    name: '',
    gender: '',
    date: [],
    begin: '',
    end: ''
  };
  // 重新查询数据库
  searchEmps();
};

/* watch监听测试代码 */
// const age = ref(0);
// watch(age, (newValue, oldValue) => {
//   console.log(`age: ${oldValue} -> ${newValue}`);
// })

// 监听对象中一个属性：date数组的变化
watch(() => searchEmp.value.date, (newValue, oldValue) => {
  searchEmp.value.begin = newValue[0];
  searchEmp.value.end = newValue[1];
})

/* 深度监听的语法 */
// watch(searchEmp, (newValue, oldValue) => {
//   console.log(newValue)
// }, { deep: true, immediate: true })  // deep: true: 深度监听, 可以监听整个对象 immediate: true: 立即监听

/* 新增员工按钮 */
const add = () => {
  // 清空表单
  employee.value = {
    username: '',
    name: '',
    gender: '',
    phone: '',
    job: '',
    salary: '',
    deptId: '',
    entryDate: '',
    image: '',
    exprList: []
  }

  
  
  // 显示新增员工模态框
  dialogVisible.value = true;
  // 给表单起个名字
  dialogTitle.value = '新增员工'
}

/* 批量删除按钮 */
const batchDelete = () => {
  //1.弹出一个确认框
  ElMessageBox.confirm('此操作将永久删除该员工, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {//确定
    //2.发送请求删除员工
    const result = await deleteEmpApi(selectedIds.value);
    if (result.code) {
      //提示删除成功
      ElMessage.success('删除成功');
      //4.刷新数据
      searchEmps();
    }
  }).catch(() => {//取消
    //5.取消删除
    ElMessage.info('已取消删除');
  });
}

/* 员工列表展示相关 */
// 员工数据
const empList = ref([]);

// 获取职位标题
function getJobTitle(job) {
  switch (job) {
    case 1:
      return '班主任';
    case 2:
      return '讲师';
    case 3:
      return '学工主管';
    case 4:
      return '教研主管';
    case 5:
      return '咨询师';
    default:
      return '其他';
  }
}

// 编辑员工
const update = async (id) => {
  console.log('Edit:', id);
  //1.展示对话框
  dialogVisible.value = true;
  //2.修改对话框标题
  dialogTitle.value = '修改员工';
  //3.查询员工信息用来回显
  const result = await getEmpByIdApi(id);
  employee.value = result.data;
  //4.处理入职日期,将begin和end封装到exprDate数组中
  const exprList = employee.value.exprList;
  //判断有工作经历就遍历,处理日期
  if(exprList && exprList.length > 0){
    exprList.forEach(expr => {
      expr.exprDate = [expr.begin, expr.end];
    })
  }

}

// 删除员工
function deleteById(id) {
  console.log('Delete:', id);
  //1.弹出一个确认框
  ElMessageBox.confirm('此操作将永久删除该员工, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {//确定
    //2.发送请求删除员工
    const result = await deleteEmpApi(id);
    if (result.code) {
      //提示删除成功
      ElMessage.success('删除成功');
      //4.刷新数据
      searchEmps();
    }
  }).catch(() => {//取消
    //5.取消删除
    ElMessage.info('已取消删除');
  });
}
/* 分页相关 */
// 总记录数
const totalRecords = ref(0);

// 当前页码
const currentPage = ref(1);

// 每页显示的记录数
const pageSize = ref(10);

// 每页记录数改变时触发
function handleSizeChange(val) {
  pageSize.value = val;
  currentPage.value = 1;
  console.log('每页记录数:', val);
  // 刷新数据
  searchEmps();
}

// 当前页码改变时触发
function handleCurrentChange(val) {
  currentPage.value = val;
  console.log('当前页码:', val);
  // 刷新数据
  searchEmps();
}

// 页面加载完成后触发
onMounted(() => {
  // 刷新数据
  searchEmps();
  // 查询部门列表数据
  getDeptList();
  //获取到localStorage中的token
  const tokenStr = JSON.parse(localStorage.getItem('loginUser')).token

  console.log('token:',tokenStr);

  if(token){
    //将token设置到请求头中
    token.value = tokenStr;
  }
})

// 查询部门列表数据
const getDeptList = async () => {
  const result =  await getDeptListApi();
  depts.value = result.data;
}

// 添加员工、修改员工表单相关
//新增/修改表单
const employeeFormRef = ref(null)
const employee = ref({
  username: '',
  name: '',
  gender: '',
  phone: '',
  job: '',
  salary: '',
  deptId: '',
  entryDate: '',
  image: '',
  exprList: []
})

// 控制弹窗
const dialogVisible = ref(false)
const dialogTitle = ref('')

//文件上传
// 图片上传成功后触发
const handleAvatarSuccess = (response) => {
  console.log(response.data)  // http://...png
  employee.value.image = response.data;
}
// 文件上传之前触发
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('只支持上传图片')
    return false
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('只能上传10M以内图片')
    return false
  }
  return true
}

/* 添加工作经历 */
const addExprItem = () => {
  employee.value.exprList.push({
    company: '',
    job: '',
    begin: '',
    end: '',
    exprDate: []
  })
}

/* watch监听 */
watch(employee, (newValue, oldValue) => {
  employee.value.exprList.forEach(expr => {
    if(expr.exprDate && expr.exprDate.length == 2){
      expr.begin = expr.exprDate[0];
      expr.end = expr.exprDate[1];
    }
  })
}, { deep: true })

/* 删除工作经历 */
const deleteExprItem = (index) => {
  employee.value.exprList.splice(index, 1)
}
  
/* 保存员工信息 */
const save = async () => {
  // 校验表单填写正确后再提交
  employeeFormRef.value.validate(async (valid) => {
    if (valid) {
      //判断是否有id
      let result = null;
      if (employee.value.id) {
        //修改
        result = await updateEmpApi(employee.value)
      } else {
        //新增
        // 1.发送异步请求，保存数据
        result = await addEmpApi(employee.value)
      }
        // 2.判断保存结果成功还是失败
        if (result.code) {
          // 1.关闭对话框
          dialogVisible.value = false;
          // 2.刷新列表数据
          searchEmps();
          // 3.提示保存成功
          ElMessage.success('保存成功')
        } else {
          ElMessage.error(result.msg)
        }
      
    }
  })
}

// 清空表单校验规则
if (employeeFormRef.value) {
    employeeFormRef.value.clearValidate();
  }

/* 表单校验规则 */
const rules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
  ]
})

/*处理复选框选中的数据*/
const selectedIds = ref([]);  //存放选中的id

const handleSelectionChange = (rows) => {
  selectedIds.value = rows.map(row => row.id);
};

const token = ref('')
</script>

<template>
  <div>
    <h1>员工管理</h1>
    <br>
    <div class="search-bar">
      <br><br>
      <!-- <input type="text" v-model="age"> -->
      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchEmp">
        <el-form-item label="姓名">
          <el-input v-model="searchEmp.name" placeholder="请输入员工姓名"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="searchEmp.gender" placeholder="请选择">
            <el-option label="男" value="1"></el-option>
            <el-option label="女" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="入职日期">
          <el-date-picker v-model="searchEmp.date" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" value-format="YYYY-MM-DD">
          </el-date-picker>
        </el-form-item>
        <!-- 按钮 -->
        <el-form-item>
          <el-button type="primary" @click="searchEmps">查询</el-button>
          <el-button @click="clear">清空</el-button>
        </el-form-item>
      </el-form>

      <!-- 按钮 -->
      <el-button type="primary" @click="add">+ 新增员工</el-button>
      <el-button type="danger" @click="batchDelete">- 批量删除</el-button>

      <br> <br>
      <!-- 表格 -->
      <el-table :data="empList" border stripe style="width: 100%" @selection-change="handleSelectionChange">
        <!-- 复选框列 -->
        <el-table-column type="selection" width="80" align="center"></el-table-column>

        <!-- 姓名列 -->
        <el-table-column prop="name" label="姓名" width="150" align="center"></el-table-column>

        <!-- 性别列 -->
        <el-table-column prop="gender" label="性别" width="120" align="center">
          <template #default="{ row }">
            {{ row.gender == '1' ? '男' : '女' }}
          </template>
        </el-table-column>

        <!-- 头像列 -->
        <el-table-column prop="image" label="头像" width="150" align="center">
          <template #default="{ row }">
            <img :src="row.image" alt="avatar" class="avatar" />
          </template>
        </el-table-column>

        <!-- 所属部门名称列 -->
        <el-table-column prop="deptName" label="所属部门" width="180" align="center"></el-table-column>

        <!-- 职位列 -->
        <el-table-column prop="job" label="职位" width="180" align="center">
          <template #default="{ row }">
            {{ getJobTitle(row.job) }}
          </template>
        </el-table-column>

        <!-- 入职日期列 -->
        <el-table-column prop="entryDate" label="入职日期" width="300" align="center"></el-table-column>

        <!-- 最后操作时间列 -->
        <el-table-column prop="updateTime" label="最后操作时间" width="300" align="center"></el-table-column>

        <!-- 操作列 -->
        <el-table-column label="操作" align="center">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="update(row.id)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteById(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <br>
      <!-- 分页组件 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="totalRecords">
      </el-pagination>
    </div>
    <!-- 新增/修改员工的对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle">
      <el-form ref="employeeFormRef" :rules="rules" :model="employee" label-width="80px">
        <!-- 基本信息 -->
        <!-- 第一行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="username" label="用户名">
              <el-input v-model="employee.username" placeholder="请输入员工用户名，2-20个字"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item prop="name" label="姓名">
              <el-input v-model="employee.name" placeholder="请输入员工姓名，2-10个字"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="gender" label="性别">
              <el-select v-model="employee.gender" placeholder="请选择性别" style="width: 100%;">
                <el-option v-for="gender in genders" :key="gender.value" :label="gender.name" :value="gender.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item prop="phone" label="手机号">
              <el-input v-model="employee.phone" placeholder="请输入员工手机号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职位">
              <el-select v-model="employee.job" placeholder="请选择职位" style="width: 100%;">
                <el-option v-for="job in jobs" :key="job.value" :label="job.name" :value="job.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="薪资">
              <el-input v-model="employee.salary" placeholder="请输入员工薪资"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第四行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属部门">
              <el-select v-model="employee.deptId" placeholder="请选择部门" style="width: 100%;">
                <el-option v-for="dept in depts" :key="dept.id" :label="dept.name" :value="dept.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入职日期">
              <el-date-picker v-model="employee.entryDate" type="date" style="width: 100%;" placeholder="选择日期"
                format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第五行 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="头像">
              <el-upload class="avatar-uploader" action="/api/upload" :show-file-list="false"
                :headers="{'token': token}"
                :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                <img v-if="employee.image" :src="employee.image" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 工作经历 -->
        <!-- 第六行 -->
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="工作经历">
              <el-button type="success" size="small" @click="addExprItem">+ 添加工作经历</el-button>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第七行 ...  工作经历 -->
        <el-row :gutter="3" v-for="(expr, index) in employee.exprList" :key="index">
          <el-col :span="10">
            <el-form-item size="small" label="时间" label-width="80px">
              <el-date-picker type="daterange" v-model="expr.exprDate" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item size="small" label="公司" label-width="60px">
              <el-input v-model="expr.company" placeholder="请输入公司名称"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item size="small" label="职位" label-width="60px">
              <el-input v-model="expr.job" placeholder="请输入职位"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="2">
            <el-form-item size="small" label-width="0px">
              <el-button type="danger" @click="deleteExprItem(index)">- 删除</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.search-bar {
  /* display: flex; */
  flex-wrap: nowrap;
  align-items: center;
}

.el-form-item {
  margin-right: 1em;
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 100%;
}

.avatar-uploader .avatar {
  width: 78px;
  height: 78px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  text-align: center;
  /* 添加灰色的虚线边框 */
  border: 1px dashed var(--el-border-color);
}
</style>